package cn.qidisoft.edu.hzjt.controller.zyc;

import cn.qidisoft.core.common.context.ApplicationContextConfigUtil;
import cn.qidisoft.core.common.log.LoggerAdapter;
import cn.qidisoft.core.common.log.LoggerAdapterFactory;
import cn.qidisoft.core.common.pagination.Page;
import cn.qidisoft.core.common.pagination.PaginationBean;
import cn.qidisoft.core.util.file.FileUtil;
import cn.qidisoft.core.util.moffice.excel.ExpExcelUtil;
import cn.qidisoft.core.web.customargument.bind.annotation.Token;
import cn.qidisoft.edu.hzjt.constants.Constant;
import cn.qidisoft.edu.hzjt.controller.BaseController;
import cn.qidisoft.edu.hzjt.exception.RPCException;
import cn.qidisoft.edu.hzjt.model.BjxxClassMaterialFile;
import cn.qidisoft.edu.hzjt.model.Employee;
import cn.qidisoft.edu.hzjt.model.ResponseResult;
import cn.qidisoft.edu.hzjt.model.UserEmployee;
import cn.qidisoft.edu.hzjt.model.zyc.ResearchProject;
import cn.qidisoft.edu.hzjt.model.zyc.ResearchProjectAtt;
import cn.qidisoft.edu.hzjt.model.zyc.ResearchProjectMember;
import cn.qidisoft.edu.hzjt.model.zyc.ResearchProjectStep;
import cn.qidisoft.edu.hzjt.service.zyc.IEmpService;
import cn.qidisoft.edu.hzjt.service.zyc.IResearchProjectService;
import cn.qidisoft.edu.hzjt.utils.CommonUtils;
import cn.qidisoft.edu.hzjt.utils.LogType;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 课题管理 提交课题Grid页面
 *
 * @author zhangwenliang
 * @Date 2018.11.29
 */
@Controller
@RequestMapping("/researchProject/")
public class ResearchProjectController {

    protected static final LoggerAdapter LOGGER = LoggerAdapterFactory.getLogger(LogType.HZJT_LOGGER.val);

    @Autowired
    private IResearchProjectService researchProjectService;

    @Autowired
    private IEmpService empService;

    private static String upload = null;

    static {
        upload = ApplicationContextConfigUtil.getString("file.path", null);
    }

    private static Map<String, List<ResearchProjectAtt>> picMap = new HashMap<>();

    /***
     * 跳转到列表页面
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "index")
    public String list(HttpServletRequest request) {
        String type = request.getParameter("type");
        request.getSession().setAttribute("type", type);
        return "zyc/researchProject/list";
    }

    /**
     * 获取列表分页数据
     *
     * @param model
     * @param request
     * @param pageSize
     * @param currentPage
     * @param partyBranch
     * @return
     */
    @RequestMapping("getListData")
    @ResponseBody
    public ResponseResult getListData(ModelMap model, HttpServletRequest request,
                                      @RequestParam(value = "rows", required = false) String pageSize,
                                      @RequestParam(value = "page", required = false) String currentPage, ResearchProject researchProject) {
        Page page = new Page();
        page.setCurrPage(currentPage == null ? 0 : Integer.valueOf(currentPage));
        page.setPageSize(pageSize == null ? 10 : Integer.valueOf(pageSize));
        BaseController.setSortByColumn(request, "createTime", "asc");
        researchProject.setOrderField((String) request.getAttribute("orderField"));
        researchProject.setOrderFlag((String) request.getAttribute("orderFlag"));
        Map<String, Object> queryMap = new HashMap<String, Object>();
        String subject = request.getParameter("subject");
        if (null != subject) {
            subject = subject.trim();
        }
        queryMap.put("subject", subject);
        String kTLB = request.getParameter("kTLB");
        if (null != kTLB) {
            kTLB = kTLB.trim();
        }
        String curStep = request.getParameter("curStep");
        if (null != curStep) {
            if (curStep.equals("0")) {
                queryMap.put("curStep", "");
            } else {
                queryMap.put("curStep", Integer.parseInt(curStep));
            }
        } else {
            queryMap.put("curStep", "");
        }
        queryMap.put("kTLB", kTLB);
        queryMap.put("beginTime", request.getParameter("beginTime"));
        queryMap.put("endTime", request.getParameter("endTime"));
        queryMap.put("ResearchProject", researchProject);
        PaginationBean<ResearchProject> paginationBean = researchProjectService.getListData(queryMap, page);
        ResponseResult result = new ResponseResult();
        result.setTotal(paginationBean.getTotalRecords());
        result.setRows(paginationBean.getPageList());
        return result;
    }

    /**
     * 跳转到填报课题添加页面
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "preadd")
    @Token(save = true)
    public String preadd(ModelMap model, HttpServletRequest request) {
        try {
            String type = request.getParameter("type");
            request.setAttribute("type", type);
            // 获取当前系统用户
            UserEmployee user = (UserEmployee) request.getSession().getAttribute(Constant.LOGIN_CONSOLE_USER);
            request.setAttribute("user", user);
            // 获取职工信息
            List<Employee> employees = empService.getDmplist();
            request.setAttribute("employees", employees);
            return "zyc/researchProject/add";
        } catch (Exception e) {
            LOGGER.error("获得xxxxx信息 addStudentDemoForward [{}] error," + this.getClass().getName() + "=[{}]",
                    this.getClass().getName(), e.getMessage());
            return "error/error";
        }
    }

    /**
     * 添加课题信息
     *
     * @param model
     * @param request
     * @param pM
     * @return
     */
    @RequestMapping(value = "add")
    public String add(ModelMap model, HttpServletRequest request, ResearchProject researchProject) {
        try {
            String type = request.getParameter("type");
            request.setAttribute("type", type);
            // 添加课题信息
            researchProject.setgID("1");
            researchProject.setCurStep(1);
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String today = dateFormat.format(new Date());
            researchProject.setCreateTime(today);
            researchProjectService.insert(researchProject);
            // 保存课题成员信息
            List<ResearchProjectMember> list = new ArrayList<ResearchProjectMember>();
            String kccy_id = request.getParameter("kccy_id");
            String kecy_name = request.getParameter("kccy");
            if (StringUtils.isNotEmpty(kccy_id)) {
                String[] kccyId = kccy_id.split(",");
                for (int i = 0; i < kccyId.length; i++) {
                    ResearchProjectMember rMember = new ResearchProjectMember();
                    rMember.setEmpId(Integer.parseInt(kccyId[i]));
                    rMember.setParentId(researchProject.getkTID());
                    // 判断是否存在选中的课题成员，没有添加，有则不添加
                    if (null == researchProjectService.getResearchMember(rMember)) {
                        list.add(rMember);
                    }
                }
                // 添加课题成员
                researchProjectService.insertMember(list);
            }
            /**
             * 在步骤表添加5记录，分别是1-5部，表增加一个stepStatus字段（int) 0：未保存 1：保存待提交 2：审核中 3：审核通过 4：审核退回
             * 添加的5条记录值中，stepStatus值未0
             */
            //code here
            String[] stepNames = {"填报课题", "开题报告", "中期报告", "结题报告", "研究过程及附件"};
            for (int i = 0; i < stepNames.length; i++) {
                ResearchProjectStep researchProjectStep = new ResearchProjectStep();
                researchProjectStep.setParentId(researchProject.getkTID());
                researchProjectStep.setStepIndex(i + 1);
                researchProjectStep.setStepName(stepNames[i]);
                if (i == 0) {
                    researchProjectStep.setStepStatus(1);
                    ;
                } else {
                    researchProjectStep.setStepStatus(0);
                }
                researchProjectService.insertStep(researchProjectStep);
            }
            return "redirect:./premodify?kTID="+researchProject.getkTID()+"&type=1";
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("获得xxxxx信息 addStudentDemo [{}] error," + this.getClass().getName() + "=[{}]",
                    this.getClass().getName(), e.getMessage());
            return "error/error";
        }
    }

    /**
     * 更新课题信息
     *
     * @param model
     * @param request
     * @param pM
     * @return
     */
    @RequestMapping(value = "saveProject")
    public String saveProject(ModelMap model, HttpServletRequest request, ResearchProject researchProject) {
        try {
            researchProjectService.update(researchProject);
            // 保存课题成员信息
            List<ResearchProjectMember> list = new ArrayList<ResearchProjectMember>();
            String kccy_id = request.getParameter("kccy_id");
            String kecy_name = request.getParameter("kccy");
            // 删除课题成员
            if (StringUtils.isNotEmpty(kccy_id)) {
                researchProjectService.deletekTCY(researchProject.getkTID());
            }
            if (StringUtils.isNotEmpty(kccy_id)) {
                String[] kccyId = kccy_id.split(",");
                for (int i = 0; i < kccyId.length; i++) {
                    ResearchProjectMember rMember = new ResearchProjectMember();
                    rMember.setEmpId(Integer.parseInt(kccyId[i]));
                    rMember.setParentId(researchProject.getkTID());
                    // 判断是否存在选中的课题成员，没有添加，有则不添加
                    //if (null == researchProjectService.getResearchMember(rMember)) {
                    list.add(rMember);
                    //}
                }
                // 添加课题成员
                researchProjectService.insertMember(list);
            }
            return "redirect:./premodify?kTID="+researchProject.getkTID()+"&type=1";
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("获得xxxxx信息 addStudentDemo [{}] error," + this.getClass().getName() + "=[{}]",
                    this.getClass().getName(), e.getMessage());
            return "error/error";
        }
    }

    /**
     * 跳转到浏览页面
     *
     * @param request
     * @return
     */
    @RequestMapping("premodify")
    public String premodify(HttpServletRequest request) {
        String type = request.getParameter("type");
        request.setAttribute("type", type);
        //获取当前系统用户
        UserEmployee user = (UserEmployee) request.getSession().getAttribute(Constant.LOGIN_CONSOLE_USER);
        request.setAttribute("user", user);
        String kTID = request.getParameter("kTID");
        //获取课题信息
        ResearchProject researchProject = researchProjectService.getByKTID(Integer.parseInt(kTID));
        if(null != researchProject.getCreateTime()) {
        	researchProject.setCreateTime(researchProject.getCreateTime().substring(0, researchProject.getCreateTime().length()-2));        	
        }
        if(null != researchProject.getkTSJ()) {
        	researchProject.setkTSJ(researchProject.getkTSJ().substring(0, researchProject.getkTSJ().length()-2));        	
        }
        for (int i = 0; i < researchProject.getResearchProjectSteps().size(); i++) {
            ResearchProjectStep researchProjectStep = researchProject.getResearchProjectSteps().get(i);
            if(null != researchProjectStep.getStepTime()) {
            	researchProjectStep.setStepTime(researchProjectStep.getStepTime().substring(0, researchProjectStep.getStepTime().length()-2));        	
            }
            if(null != researchProjectStep.getAuditeTime()) {
            	researchProjectStep.setAuditeTime(researchProjectStep.getAuditeTime().substring(0, researchProjectStep.getAuditeTime().length()-2));        	
            }
            
            request.setAttribute("researchProjectStep" + (i + 1), researchProjectStep);
        }
        // 获取课程成员信息
        // 根据课题id 查找成员

        String kccy_id = "";
        String kccy_name = "";
        List<Employee> eList = new ArrayList<Employee>();
        if (researchProject.getResearchProjectMembers().size() != 0) {
            for (int i = 0; i < researchProject.getResearchProjectMembers().size(); i++) {
                if ((i + 1) % 5 == 0) {
                    ResearchProjectMember rProject = researchProject.getResearchProjectMembers().get(i);
                    Employee emp = empService.getDmpId(rProject.getEmpId());
                    if(null != emp) {
                    	kccy_name += emp.getXm() + ",";
                    	kccy_id += emp.getEmid() + ",";
                    	Employee employee = new Employee();
                    	employee.setEmid(emp.getEmid());
                    	employee.setXm(emp.getXm());
                    	eList.add(employee);                    	
                    }
                }
            }
            
            // 获取职工信息
            List<Employee> employees = empService.getDmplist();
            request.setAttribute("employees", employees);
            if(kccy_id.length() != 0) {
            	request.setAttribute("kccy_id", kccy_id.substring(0, kccy_id.length() - 1));
            	request.setAttribute("kccy_name", kccy_name.substring(0, kccy_name.length() - 1));            	
            }else {
            	request.setAttribute("kccy_id", kccy_id);
            	request.setAttribute("kccy_name", kccy_name);            	
            }
        	request.setAttribute("eList", eList);
        }
        request.setAttribute("researchProject", researchProject);

        //获取附件信息
        ResearchProjectAtt att = new ResearchProjectAtt();
        att.setParentId(Integer.parseInt(kTID));
        request.setAttribute("type", type);
        List<ResearchProjectAtt> attList = researchProjectService.queryList(att);
        request.setAttribute("dataList", attList);
        return "zyc/researchProject/modify";
    }

    /**
     * 更新步骤信息
     *
     * @param model
     * @param request
     * @param pM
     * @return
     */
    @RequestMapping(value = "save")
    public String save(ModelMap model, HttpServletRequest request, ResearchProjectStep researchProjectStep) {
        try {
            String type = request.getParameter("type");
            request.setAttribute("type", type);
            String kTID = request.getParameter("kTID");
            researchProjectService.updateStep(researchProjectStep);
            if (researchProjectStep.getStepIndex() == 5) {

                UserEmployee userEmployee =
                        (UserEmployee) request.getSession().getAttribute(Constant.LOGIN_CONSOLE_USER);

                String path = upload;
                List<ResearchProjectAtt> docFileResourceList = picMap.get(String.valueOf(userEmployee.getUserid()));
                if (docFileResourceList != null && !docFileResourceList.isEmpty()) {
                    MultipartFile file = null;
                    String filePath = CommonUtils.createSaveFilePath("JKY_JKS_TJKT", userEmployee.getUserid());
                    int orders = 0;
                    for (ResearchProjectAtt r : docFileResourceList) {
                        file = r.getMufile();
                        r.setParentId(Integer.parseInt(kTID));
                        String name = file.getOriginalFilename();// 获取上传文件名
                        InputStream in = r.getInputStream();// 获取文件对象
                        int pos = name.lastIndexOf(".");
                        String lastname = name.substring(pos, name.length());
                        // 文件保存的路径
                        String savePath = path + CommonUtils.fileSeprator + filePath;
                        FileUtil.saveFile(savePath, in, r.getGid() + lastname);
                        r.setGid(r.getGid());// 附件id
                        r.setFileName(name);
                        r.setOrders(orders);
                        orders++;
                    }
                    researchProjectService.batchInserts(docFileResourceList);
                    //保存成功后，清除明细
                    picMap.remove(String.valueOf(userEmployee.getUserid()));
                }
                BaseController.setParameter("msg", "添加成功");
            }

            return "redirect:./premodify?kTID="+kTID+"&type=1";
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("获得xxxxx信息 addStudentDemo [{}] error," + this.getClass().getName() + "=[{}]",
                    this.getClass().getName(), e.getMessage());
            return "error/error";
        }
    }

    /**
     * 提交
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "setStepStatus")
    public String setStepStatus(HttpServletRequest request, ResearchProjectStep researchProjectStep) {
        //修改步骤审核表
        String kTID = request.getParameter("kTID");
        ResearchProjectStep researchProjectStep2 = new ResearchProjectStep();
        researchProjectStep2.setStepStatus(2);
        researchProjectStep2.setStepId(researchProjectStep.getStepId());
        researchProjectService.updateStep(researchProjectStep2);
        return "redirect:./premodify?kTID="+kTID+"&type=1";

    }

    /**
     * 课题审核 同意
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "agree")
    public String agree(HttpServletRequest request, ResearchProjectStep researchProjectStep) {
        UserEmployee user = (UserEmployee) request.getSession().getAttribute(Constant.LOGIN_CONSOLE_USER);
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String formatStr = formatter.format(new Date());
        //修改步骤审核表
        String kTID = request.getParameter("kTID");
        ResearchProjectStep researchProjectStep2 = new ResearchProjectStep();
        researchProjectStep2.setStepStatus(3);
        researchProjectStep2.setAuditorId(user.getUid());
        researchProjectStep2.setAuditorName(user.getName());
        researchProjectStep2.setAuditeTime(formatStr);
        researchProjectStep2.setStepId(researchProjectStep.getStepId());
        researchProjectStep2.setAuditSuggestion(researchProjectStep.getAuditSuggestion());
        researchProjectService.updateStep(researchProjectStep2);
        ResearchProject researchProject = new ResearchProject();
        researchProject.setCurStep(researchProjectStep.getStepIndex() + 1);
        researchProject.setkTID(Integer.parseInt(kTID));
        researchProjectService.update(researchProject);
        return "redirect:./premodify?kTID="+kTID+"&type=2";
    }

    /**
     * 课题审核 不同意
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "disAgree")
    public String disAgree(HttpServletRequest request, ResearchProjectStep researchProjectStep) {
        UserEmployee user = (UserEmployee) request.getSession().getAttribute(Constant.LOGIN_CONSOLE_USER);
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String formatStr = formatter.format(new Date());
        //修改步骤审核表
        String kTID = request.getParameter("kTID");
        String auditSuggestion = request.getParameter("auditSuggestion");
        if (null == auditSuggestion) {
            auditSuggestion = "";
        }
        ResearchProjectStep researchProjectStep2 = new ResearchProjectStep();
        researchProjectStep2.setStepStatus(4);
        researchProjectStep2.setAuditorId(user.getUid());
        researchProjectStep2.setAuditorName(user.getName());
        researchProjectStep2.setAuditeTime(formatStr);
        researchProjectStep2.setStepId(researchProjectStep.getStepId());
        researchProjectStep2.setAuditSuggestion(auditSuggestion);
        researchProjectService.updateStep(researchProjectStep2);
        return "redirect:./premodify?kTID="+kTID+"&type=2";
    }

    /**
     * 删除课题信息
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "delete", method = RequestMethod.POST)
    public String delete(ModelMap model, HttpServletRequest request) {
        try {
            String[] idList = request.getParameter("idList").split(",");
            List<Integer> list = new ArrayList<>();
            for (int i = 0; i < idList.length; i++) {
                list.add((Integer.valueOf(idList[i])));
            }
            if (list.size() != 0) {
                researchProjectService.delete(list);
            }
            BaseController.setParameter("msg", "删除成功");
            return "redirect:index";
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("删除 delete [{}] error," + this.getClass().getName() + "=[{}]", this.getClass().getName(),
                    e.getMessage());
            return "error/error";
        }
    }

    /**
     * 课题下载
     *
     * @param form
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "export_df")
    public @ResponseBody
    void export_dzb(HttpServletRequest request, HttpServletResponse response,
                    ResearchProject pDues) throws Exception {
        try {
            Map<String, Object> queryMap = new HashMap<String, Object>();
            String subject = request.getParameter("subject");
            if (null != subject) {
                subject = subject.trim();
            }
            queryMap.put("subject", subject);
            String kTLB = request.getParameter("kTLB");
            if (null != kTLB) {
                kTLB = kTLB.trim();
            }
            String curStep = request.getParameter("curStep");
            if (null != curStep) {
                if (curStep.equals("0")) {
                    queryMap.put("curStep", "");
                } else {
                    queryMap.put("curStep", Integer.parseInt(curStep));
                }
            } else {
                queryMap.put("curStep", "");
            }
            queryMap.put("kTLB", kTLB);
            queryMap.put("beginTime", request.getParameter("beginTime"));
            queryMap.put("endTime", request.getParameter("endTime"));
            List<ResearchProject> datalist = researchProjectService.getResearchProjectList(queryMap);
            String[][] title_name = {{"提交课题Id", "标题", "类别", "时间", "进度", "提交时间"}};
            String[] title_style = {"hwzs_16_bold_25", "hwzs_16_bold_25", "hwzs_16_bold_25", "hwzs_16_bold_25",
                    "hwzs_16_bold_25", "kt_12_bold_18"};
            String fileName = "提交课题";
            String[] remark = {""};
            List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
            if (datalist != null && !datalist.isEmpty()) {
                for (ResearchProject res : datalist) {
                    Map<String, Object> map = new LinkedHashMap<String, Object>();
                    map.put("kTID", res.getkTID());
                    map.put("subject", res.getSubject());
                    map.put("kTLB", res.getkTLB());
                    map.put("kTSJ", res.getkTSJ());
                    map.put("curStep", res.getCurStep());
                    map.put("createTime", res.getCreateTime());
                    list.add(map);
                }
            }
            HSSFWorkbook wb = ExpExcelUtil.getWorkBookExcel(title_name, title_style, 100, remark, fileName, list);
            try {
                String filenameConvert = "提交课题";/* new String(fileName.getBytes("GB2312"), "ISO8859-1"); */
                response.reset();
                response.setContentType("application/vnd.ms-excel;charset=utf-8");
                response.setHeader("Content-Disposition",
                        "attachment;filename=" + new String((filenameConvert + ".xls").getBytes(), "iso-8859-1"));
                response.setDateHeader("Expires", 0);
                ServletOutputStream os = response.getOutputStream();
                wb.write(os);
                os.flush();
            } catch (Exception e) {
                System.out.println("网络连接断开，可能用户取消了导出");
            }
        } catch (RPCException e) {
            LOGGER.error("获得xxxxx信息 exportStudentjobList [{}] error," + this.getClass().getName() + "=[{}]",
                    this.getClass().getName(), e.getMessage());
        }
    }

    /**
     * 附件上传
     *
     * @param file
     * @param request
     * @param response
     */
    @RequestMapping(value = "/source_upload", method = RequestMethod.POST)
    public @ResponseBody
    void loadFile(@RequestParam("file") MultipartFile file,
                  HttpServletRequest request, HttpServletResponse response) {
        List<ResearchProjectAtt> list = new ArrayList<ResearchProjectAtt>();
        UserEmployee userEmployee = (UserEmployee) request.getSession()
                .getAttribute(Constant.LOGIN_CONSOLE_USER);
        List<ResearchProjectAtt> docFileResourceList = picMap
                .get(String.valueOf(userEmployee.getUserid()));
        // 本地env配置路径
        String path = upload;
        try {
            String gid = UUID.randomUUID().toString();
            String name = file.getOriginalFilename();// 获取上传文件名
            // 获取文件后缀名称
            String extend = FilenameUtils.getExtension(name);
            ResearchProjectAtt docFile = new ResearchProjectAtt();
            String filePath = CommonUtils.createSaveFilePath("JKY_JKS_TJKT", userEmployee.getUserid());
            if (!file.isEmpty()) {
                // 文件的大小
                docFile.setFileSize(String.valueOf(FileUtil.FormetFileSize(Long.valueOf(file.getSize()))));
                docFile.setFileName(name);
                docFile.setGid(gid);
                docFile.setExtension(FileUtil.getFileExtendName(name).toLowerCase());
                docFile.setMufile(file);
                docFile.setInputStream(file.getInputStream());
                /**
                 * 2018年12月9日
                 * 当前业务目录/用户ID/上传当前时间（到天）/随机生成uuid文件名称
                 */
                docFile.setFilePath(filePath + gid + "." + extend);
                docFile.setSysfilepath(path + CommonUtils.fileSeprator + filePath + gid + "." + extend);

                docFile.setOrders(0);

                if (docFileResourceList != null && docFileResourceList.size() > 0) {
                    docFileResourceList.add(docFile);
                    picMap.put(String.valueOf(userEmployee.getUserid()), docFileResourceList);
                } else {
                    list.add(docFile);
                    picMap.put(String.valueOf(userEmployee.getUserid()), list);
                }
                LOGGER.info("附件上传成功！");
            }
            PrintWriter writer = null;
            BjxxClassMaterialFile docFile2 = new BjxxClassMaterialFile();
            docFile2.setFilepath(docFile.getFilePath());
            // 文件名称
            docFile2.setFilename(docFile.getFileName());
            docFile2.setSysfilepath(path + CommonUtils.fileSeprator + filePath + gid + "." + extend);
            writer = response.getWriter();
            String json = JSONObject.toJSONString(docFile2);
            writer.write(json);
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * @Title: source_upload_update @Description: 删除附件 @param @param
     * fileId @param @param request @param @param response @param @return
     * 参数 @return Map<String,Object> 返回类型 @throws
     */
    @RequestMapping(value = "/source_upload_update", method = RequestMethod.POST)
    public @ResponseBody
    Map<String, Object> source_upload_update(@RequestParam("fileId") String fileId,
                                             @RequestParam("filePath") String filePath, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> dataMap = new HashMap<String, Object>();
        try {
            // 删除表记录
            ResearchProjectAtt attEntity = new ResearchProjectAtt();
            attEntity.setFileId(Integer.parseInt(fileId));

            ResearchProjectAtt newAttEntity = researchProjectService.queryByFileId(attEntity);
            filePath = newAttEntity.getFilePath();
            researchProjectService.deleteAccessory(attEntity);

            // 删除原始文件
            File file = new File(upload + CommonUtils.fileSeprator + filePath);
            file.delete();

            //删除目录：实际上是删除最后一节也就是日期文件夹
//			try {
//				FileUtils.forceDelete(new File(upload + File.separator + filePath.substring(0,filePath.lastIndexOf("\\")))); //如果文件中所有的文件被删除了，还需要删除文件目录
//			} catch (Exception e) {
//
//			}
            dataMap.put("success", "0000");
        } catch (Exception e) {
            LOGGER.error("调用services网络异常", e);
            dataMap.put("success", "-9999");

        }
        return dataMap;
    }


    @InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        dateFormat.setLenient(false);
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));

    }
}
